#! /usr/bin/sdlbrt
'- from Paulo Silva, GPL license, december '10
'-   captures picture from a webcam (b&w version), converts to Atari800 .bin (.cas), and sends the .cas sound to a CoCo2 via mic cable
'- dependencies:
'-   sudo apt-get install perl python sox imagemagick sdlbrt fswebcam
'-   sudo apt-get install xawtv vgrabbj music123 lame mpg123 sdlbasic
'- needed:
'-   a linux computer with a working webcam (like using uvcvideo) and all needed packages installed
'-   a coco2 running a simple cloadm code into a pmode, and connected by audio cable to a linux computer (like on a cassette player)
'-   sdlbasic for running this code
'- the code converts a 160x192 2c picture into a 'graphics14' binary file
setdisplay(160,192,32,1):paper(8^8-1):ink(0):pen(0):cls
captool$="fswebcam"
fout$="_.bin"
while 0=0
  if captool$="vgrabbj" then
    setcaption("dummy")
    shell("vgrabbj -d /dev/video0 -F 4 -f _1.jpg")
    setcaption("del")
    shell("rm _1.jpg")
    setcaption("webcam")
    shell("vgrabbj -d /dev/video0 -F 4 -f _1.jpg")
    end if
  if captool$="fswebcam" then
    setcaption("del")
    shell("rm _1.jpg")
    setcaption("webcam")
    shell("fswebcam -d /dev/video0 _1.jpg")
    end if
  setcaption("imagemagick")
  shell("convert _1.jpg -resize 160x192\\! _2.jpg")  '- shell("convert _tmpr1.jpg -resize 160x192\\! -level 0,80%,1 _tmpr2.jpg")
  setcaption("del")
  shell("rm _1.jpg")
  setcaption("load")
  loadimage("_2.jpg",1):pasteicon(0,0,1)
  setcaption("del")
  shell("rm _2.jpg")
  setcaption("conv")
  open fout$ for output as #1
  dim clust[8,8]:a$="00,06,08,14,02,12,04,10,08,14,00,06,04,10,02,12"
  for y2=0 to 3:for x2=0 to 3:lc=(y2*4)+x2:clust[x2,y2]=val(mid$(a$,(lc*3)+1,2)):next:next
  for y=0 to 191
    for x1=0 to 19
      btv=0:btt=0
      for x2=7 to 0 step -1
        x=x1*8+(7-x2)
        btv=btv*2
        u=point(x,y)
        b=u mod 256: u=int(u/256)
        g=u mod 256: u=int(u/256)
        r=u mod 256: u=int(u/256)
        w=int(((b*11)+(r*30)+(g*59))/100)
        patgf=(((clust[x mod 4,y mod 4]+1)*255)/16)
        btt=0:ink(0x000000):if w>patgf then:btt=1:ink(0xFFFFFF):end if
        dot(x,y)
        btv=btv+btt
        next
      writebyte(1,btv)
      next:next
  grab(1,0,0,160,192):saveimage("_.bmp",1):shell("convert _.bmp _.png && rm _.bmp")
  close #1
  'setcaption("bin2cas...")
  'shell("python bin2cas.py "+fout$)
  'setcaption(".cas log...")
  'shell("cat "+fout$+".cas >> _log.cas")
  'setcaption("cas2wav...")
  'foutw$="_.wav"
  'shell("perl cas2wav.pl "+fout$+".cas "+foutw$ )
  'setcaption("erasing temporary files...")
  'shell("rm _.bin _.bin.cas _.png")
  'setcaption("sox play...")
  'shell("play _.wav")
  'setcaption("erasing temporary files...")
  'shell("rm _.wav")
  wend
